package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Override
	public List<LiveRoom> findLiveList() {
		//	查询所有正在直播的列表
		return liveRoomMapper.selectList(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getStatus,"1").gt(LiveRoom::getExpireTime,new Date()));
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo, Long userId) {
		//	创建对象
		LiveRoom liveRoom = new LiveRoom();
		//	属性拷贝：
		BeanUtils.copyProperties(liveRoomVo,liveRoom);
		liveRoom.setUserId(userId);
		liveRoom.setStatus("1");
		liveRoom.setAppName("live");
		liveRoom.setStreamName("room"+userId);
		//	获取过期时间
		Long txTime = liveRoomVo.getExpireTime().getTime()/ 1000;
		//	使用工具类获取：
		TencentLiveAddressVo liveAddressVo = LiveAutoAddressUtil.getAddressUrl(liveRoom.getStreamName(), txTime);
		//	推流地址
		liveRoom.setPushUrl(liveAddressVo.getPushWebRtcUrl());
		//	拉流地址
		liveRoom.setPlayUrl(liveAddressVo.getPullWebRtcUrl());
		//	保存数据
		this.save(liveRoom);
		//	返回数据
		return liveRoom;
	}

	@Override
	public LiveRoom getCurrentLive(Long userId) {
		//	正在直播，谁的直播
		return liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId,userId).eq(LiveRoom::getStatus,"1").gt(LiveRoom::getExpireTime,new Date()));
	}
}
